package com.aiyi.server.manager.nginx.controller;


import javax.servlet.http.HttpSession;
import javax.validation.ValidationException;

import com.aiyi.server.manager.nginx.utils.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.aiyi.server.manager.nginx.bean.User;
import com.aiyi.server.manager.nginx.bean.result.Result;
import com.aiyi.server.manager.nginx.common.CommonFields;
import java.io.UnsupportedEncodingException;
import java.util.Base64;

/**
 * 登陆控制器
 *
 * @Project : nginx
 * @Program Name : com.aiyi.server.manager.nginx.controller.LoginController
 * @Description :
 * @Author : 崔辉
 * @Creation Date : 2021年9月9日 上午11:14:59
 * @ModificationHistory Who When What ---------- ------------- -----------------------------------
 * 崔辉 2021年9月9日 create
 */
@Controller
public class LoginController {

    @RequestMapping("/")
    public String index() {
        return "login";
    }

    @Autowired
    private Environment env;

    @RequestMapping("login")
    @ResponseBody
    public Result login(@RequestBody User user, HttpSession session) {
        if (null == user.getUsername() || "".equals(user.getUsername().trim())) {
            throw new ValidationException("请填写用户名");
        }
        if (null == user.getPassword() || "".equals(user.getPassword())) {
            throw new ValidationException("请填登陆密码");
        }

        //配置信息移至yaml文件,获取密文密码
        String string = env.getProperty(CommonFields.PROP.ACCOUNT + "." + user.getUsername());
        //生成密文密码
        String passwdEnc = MD5Util.getMD5(user.getUsername(),user.getPassword());
        if (null == string || !string.equals(passwdEnc)) {
            throw new ValidationException("用户名或密码错误");
        }
        session.setAttribute(CommonFields.SESSION_KEY.LOGIN_USER, user.getUsername());
        Result result = new Result();
        result.setSuccess(true);
        return result;
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session) {
        session.removeAttribute(CommonFields.SESSION_KEY.LOGIN_USER);
        return "redirect:/";
    }

    public static void main(String[] args) throws UnsupportedEncodingException {
        //base64加解密
        Base64.Encoder encoder = Base64.getEncoder();
        Base64.Decoder decoder = Base64.getDecoder();
        String encodeStr = encoder.encodeToString("admin".getBytes("UTF-8"));
        System.out.println("加密后----->" + encodeStr);
        String decodeStr = new String(decoder.decode(encodeStr),"UTF-8");
        System.out.println("解密后----->" + decodeStr);

        //MD5加密

    }
}
